# Maintainer: David Runge <dvzrv@archlinux.org>

_name=PyMuPDF
pkgname=python-pymupdf
pkgver=1.22.2
pkgrel=2
pkgdesc="Python bindings for MuPDF's rendering library"
arch=(loong64 x86_64)
url="https://github.com/pymupdf/PyMuPDF"
license=(AGPL3)
depends=(
  glibc
  gumbo-parser
  jbig2dec
  libmupdf
  openjpeg2
  python
)
makedepends=(
  freetype2
  git
  libjpeg-turbo
  python-build
  python-distro
  python-installer
  python-setuptools
  python-wheel
  swig
  systemd
)
checkdepends=(
  python-fonttools
  python-pillow
  python-pytest
)
optdepends=(
  'python-fonttools: for building font subsets using fontTools'
  'python-pillow: for image file saving using pillow'
)
source=(
  https://files.pythonhosted.org/packages/source/${_name::1}/$_name/$_name-$pkgver.tar.gz
)
sha512sums=('6b302fb6e23bb6f91698dd9e87dce2bc7c6c6b3e7d76a35111939f9a14034865908b26f5d3e30c31d10520c9906ff596a0fff0548ede8c0a0fd61968e153b706')
b2sums=('6b79128929d1a4604efc720deb3efa53dd4005228e72dd207ebb8e2d501c6748cca8ab1dffde0fe41216ccbcad2a5c2763516c430e6fc626ce5c37093565807f')

prepare() {
  # remove bundled mupdf sources
  rm -frv $pkgname/*.tgz
  # we package swig and don't need python-swig
  sed -e 's/, "swig"//' -i $_name-$pkgver/pyproject.toml
}

build() {
  cd $_name-$pkgver
  # NOTE: build against system libmupdf
  export PYMUPDF_SETUP_MUPDF_BUILD=""
  python -m build --wheel --no-isolation
}

check() {
  local pytest_options=(
    -vv
    # disable broken test, that upstream is not interested in fixing or disabling: https://github.com/pymupdf/PyMuPDF/issues/2127
    --deselect tests/test_pixmap.py::test_color_count
  )
  local _site_packages=$(python -c "import site; print(site.getsitepackages()[0])")

  cd $_name-$pkgver
  python -m installer --destdir=test_dir dist/*.whl
  export PYTHONPATH="$PWD/test_dir/$_site_packages:$PYTHONPATH"
  pytest "${pytest_options[@]}" tests/
}

package() {
  depends+=(
    freetype2 libfreetype.so
    libjpeg-turbo libjpeg.so
  )

  cd $_name-$pkgver
  python -m installer --destdir="$pkgdir" dist/*.whl
  install -vDm 644 README.md -t "$pkgdir/usr/share/doc/$pkgname/"
}
